package com.yunhe.history.websocket;

import com.yunhe.common.constant.MeasurementConsts;
import com.yunhe.common.model.data.Measurement;
import com.yunhe.common.websocket.WebsocketRealtimeHandler;
import com.yunhe.history.service.data.MeasurementService;
import com.yunhe.common.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取点号最新量测socket
 */
@EnableAsync
public class MeasurementLastHandler extends WebsocketRealtimeHandler {
    @Autowired
    private MeasurementService measurementService;

    @Override
    public void beforeSend(WebSocketSession session, Object content) {

    }

    @Override
    public void afterEstablished(WebSocketSession session) {

    }

    @Override
    public void afterClosed(WebSocketSession session, CloseStatus status) {

    }

    @Override
    public void handleMessage(WebSocketSession session, TextMessage message, List<String> points) {
        Map<String, Measurement> result = getMeasurementsLast(points);
        sendMessage(result, session, points);
    }

    /**
     * 每15分钟获取最新的历史量测
     */
    @Scheduled(cron = "15 0/15 * * * ?")
    public void sendMessageTask() {
        List<String> allPoint = getAllPoints();
        Map<String, Measurement> result = getMeasurementsLast(allPoint);
        sendMessage(result, null, allPoint);
    }

    /**
     * 获得点号在历史量测中的最新值
     * @param points 点号
     */
    private Map<String, Measurement> getMeasurementsLast(List<String> points) {
        Map<String, Measurement> result = new HashMap<>();
        if (CollectionUtil.isNotEmpty(points)) {
            List<Long> pointNumbers = new ArrayList<>();
            for (String point : points) {
                pointNumbers.add(Long.parseLong(point));
            }
            Map<Long, Measurement> measurementMap = measurementService.findMeasurementsLastBatch(pointNumbers,
                    MeasurementConsts.FREQUENCY.Original.value(), null, null);
            if (measurementMap != null) {
                measurementMap.forEach((point, measurement) -> {
                    if (measurement != null) {
                        result.put(String.valueOf(point), measurement);
                    }
                });
            }
        }
        return result;
    }
}
